//
//  GKSearchResultController.swift
//  MySwiftObject
//
//  Created by wangws1990 on 2019/9/20.
//  Copyright © 2019 wangws1990. All rights reserved.
//

import UIKit

class GKSearchResultController: BaseTableViewController {

    var keyWord : String!;
    lazy var listData : [GKBookModel] = {
        return []
    }()
    class func vcWithKeyWord(keyWord : String) ->GKSearchResultController{
        let vc :GKSearchResultController = self.init();
        vc.keyWord = keyWord;
        return vc;
    }
    override func viewDidLoad() {
        super.viewDidLoad()
        self.showNavTitle(title: self.keyWord)
        self.setupEmpty(scrollView: self.tableView);
        self.setupRefresh(scrollView: self.tableView, options:.Default);
    }
    override func refreshData(page: Int) {
        GKClassifyNetManager.bookSearch(hotWord: self.keyWord, page: page, size: 20, sucesss: { (object) in
            if page == 1{
                self.listData.removeAll();
            }
            if object is NSDictionary{
                let dic :NSDictionary = object as! NSDictionary;
                let datas : NSArray = dic["books"] as! NSArray;
                for objc in datas{
                    let ovj : NSDictionary = objc as! NSDictionary;
                    let model : GKBookModel = GKBookModel.deserialize(from: ovj)!
                    self.listData.append(model);
                }
                self.tableView.reloadData();
                self.endRefresh(more: datas.count >= 20);
            }
            
        }) { (error) in
            self.endRefreshFailure();
        }
    }
    override func numberOfSections(in tableView: UITableView) -> Int {
        return 1;
    }
    override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return self.listData.count;
    }
    override func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
        return UITableViewAutomaticDimension
    }
    override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let cell : GKClassifyTailCell = GKClassifyTailCell.cellForTableView(tableView: tableView, indexPath: indexPath);
        cell.model = self.listData[indexPath.row];
        return cell;
    }
    override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
        tableView.deselectRow(at: indexPath, animated: true)
        let model :GKBookModel = self.listData[indexPath.row];
        GKJump.jumpToDetail(bookId: model.bookId);

    }
}
